<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-form
        :inline="true"
        class="demo-form-inline"
        style="width: max-content"
      >
        <el-form-item label="文章类型：">
          <el-select
            v-model="filterForm.categoryId"
            placeholder="请选择类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="文章标题：">
          <el-input
            v-model="filterForm.title"
            placeholder="请输入标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="发布时间：">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 310px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
          <!-- 添加新闻按钮 -->
          <!-- <el-button type="primary" @click="handleAddNews" style="margin-left: 5px;"> 添加新闻</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
    >
      <el-table-column prop="contentId" label="ID" width="80" align="center" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column
        prop="username"
        label="作者"
        width="120"
        align="center"
      />
      <el-table-column prop="summary" label="摘要" min-width="180" />
      <el-table-column
        prop="publishTime"
        label="发表时间"
        width="160"
        :formatter="formatDate"
      />
      <el-table-column
        prop="contentStatus"
        label="状态"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-select
            v-model="row.statusCode"
            placeholder="请选择"
            @change="(value) => handleStatusChange(row.contentId, value)"
            size="small"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row)">查看</el-link>
          <el-divider direction="vertical" />
          <el-link type="success" @click="handleEdit(row)">编辑</el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" @click="handleDelete(row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      class="pagination-container"
      v-model:current-page="current"
      v-model:page-size="size"
      :page-sizes="[3, 5, 10, 20]"
      :background="true"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新闻详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" width="60%" top="5vh">
      <div class="detail-header">
        <h2>{{ currentNews.title }}</h2>
        <div class="detail-meta">
          <span
            ><i class="el-icon-user"></i> 作者：{{ currentNews.username }}</span
          >
          <span
            ><i class="el-icon-time"></i> 发布时间：{{
              formatDate(currentNews.publishTime)
            }}</span
          >
          <span
            ><i class="el-icon-collection-tag"></i> 分类：{{
              getCategoryName(currentNews.categoryId)
            }}</span
          >
          <span class="detail-content">摘要：{{ currentNews.summary }}</span>
        </div>

        <el-row :gutter="20" class="stats-row">
          <el-col :span="12">
            <div class="stat-item">
              <i class="el-icon-view"></i> 阅读量：{{
                currentNews.readCount || 0
              }}
            </div>
            <div class="stat-item">
              <i class="el-icon-share"></i> 分享量：{{
                currentNews.shareCount || 0
              }}
            </div>
          </el-col>

          <el-col :span="12">
            <div class="stat-item">
              <i class="el-icon-document"></i> 来源：{{
                formatSourceType(currentNews.sourceType)
              }}
            </div>
            <div class="stat-item">
              <i class="el-icon-s-flag"></i> 状态：{{
                currentNews.contentStatus
              }}
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="detail-content" v-html="currentNews.content"></div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑新闻" width="70%">
      <news-edit-dialog
        v-if="editDialogVisible"
        ref="editDialog"
        :form-data="currentEditData"
        @submit-success="handleEditSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import axios from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import NewsEditDialog from "./news-edit-dialog.vue";

export default {
  components: {
    NewsEditDialog,
  },
  data() {
    return {
      // 筛选表单
      filterForm: {
        title: "",
        categoryId: "",
        dateRange: [],
      },
      // 分类选项
      categoryOptions: [],
      tableData: [],
      loading: false,
      // 分页配置
      current: 1,
      size: 10,
      total: 0,
      // 详情弹窗
      detailDialogVisible: false,
      currentNews: {},
      // 编辑弹窗
      editDialogVisible: false,
      currentEditData: {},
      // 状态选项
      statusOptions: [
        { value: 1, label: "草稿" },
        { value: 2, label: "待审核" },
        { value: 3, label: "已发布" },
        { value: 4, label: "已封禁" },
        { value: 5, label: "已删除" },
      ],
    };
  },
  methods: {
    // 获取新闻列表数据
    showData() {
      this.loading = true;
      axios
        .get("/contents/page", {
          params: {
            current: this.current,
            size: this.size,
            categoryId: this.filterForm.categoryId,
            title: this.filterForm.title,
            ...(this.filterForm.dateRange &&
              this.filterForm.dateRange.length === 2 && {
                startTime: this.filterForm.dateRange[0],
                endTime: this.filterForm.dateRange[1],
              }),
          },
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.categoryOptions = response.data.data.categoriesList || [];
            this.tableData = response.data.data.contentsPage.records || [];
            this.total = response.data.data.contentsPage.total || 0;
            this.current = response.data.data.contentsPage.current || 1;
          } else {
            ElMessage.error(response.data.msg || "获取数据失败");
          }
        })
        .catch((err) => {
          console.error("获取新闻列表失败:", err);
          ElMessage.error("获取新闻列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.size = val;
      this.current = 1;
      this.showData();
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.current = val;
      this.showData();
    },

    // 搜索处理
    handleSearch() {
      this.current = 1;
      this.showData();
    },

    // 重置表单
    resetForm() {
      this.filterForm = {
        title: "",
        categoryId: "",
        dateRange: [],
      };
      this.handleSearch();
    },

    // 删除新闻
    handleDelete(row) {
      ElMessageBox.confirm(`确定要删除新闻 "${row.title}" 吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete("/admin/contents/delete", {
              params: {
                contentId: row.contentId,
              },
            })
            .then((resp) => {
              if (resp.data.code === 200) {
                ElMessage.success("删除成功");
                this.showData();
              } else {
                ElMessage.error(resp.data.msg || "删除失败");
              }
            })
            .catch((err) => {
              console.error("删除新闻失败:", err);
              ElMessage.error("删除失败，请重试");
            });
        })
        .catch(() => {
          // 用户取消删除
        });
    },

    // 格式化日期
    formatDate(row, column, cellValue) {
      if (!cellValue) return "";
      const date = new Date(cellValue);
      return date.toISOString().split("T")[0];
    },

    // 格式化来源类型
    formatSourceType(type) {
      const map = { 1: "原创", 2: "转载", 3: "翻译" };
      return map[type] || "未知来源";
    },

    // 获取分类名称
    getCategoryName(id) {
      if (!id || !this.categoryOptions) return "未知分类";
      const category = this.categoryOptions.find(
        (cat) => cat.categoryId === id
      );
      return category ? category.categoryName : "未知分类";
    },

    // 查看详情
    handleView(row) {
      this.currentNews = row;
      this.detailDialogVisible = true;
    },

    // 编辑新闻
    handleEdit(row) {
      this.currentEditData = { ...row };
      this.editDialogVisible = true;
    },

    // 编辑成功回调
    handleEditSuccess() {
      this.editDialogVisible = false;
      this.showData();
      ElMessage.success("新闻更新成功");
    },

    // 处理状态改变
    handleStatusChange(contentId, statusCode) {
      axios.post('/contents/updateStatus', {
        contentId,
        statusCode
      })
      .then(response => {
        if (response.data.code === 200) {
          ElMessage.success('状态更新成功');
          this.showData();
        } else {
          ElMessage.error(response.data.msg || '状态更新失败');
       }
      })
      .catch(error => {
        console.error('状态更新失败:', error);
       ElMessage.error('状态更新失败');
      });
    },
  },
  created() {
    this.showData();
  },
};
</script>

<style scoped>
.filter-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-header {
  padding-bottom: 15px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h2 {
  font-size: 1.8rem;
  color: #1f2d3d;
  margin-bottom: 10px;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 25px;
  color: #606266;
  margin-bottom: 15px;
}

.detail-content {
  line-height: 1.8;
  font-size: 16px;
}

.detail-content img {
  max-width: 100%;
  margin: 15px 0;
  border-radius: 8px;
}

.detail-content p {
  margin-bottom: 15px;
}

.stats-row {
  margin-top: 15px;
}

.stat-item {
  margin-bottom: 10px;
  color: #666;
}

.el-link {
  margin-right: 8px;
}
</style>
